package com.isoft.service.impl;

import com.isoft.entity.DfmeRtneEntity;
import com.isoft.mapper.DfmeRtneMapper;
import com.isoft.service.DfmeRtneService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeRtneServiceImpl implements DfmeRtneService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeRtneServiceImpl.class);

    @Autowired
    private DfmeRtneMapper dfmeRtneMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-RTNE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void parseAndSave(DfmeRtneEntity entity) {
        if (entity == null || entity.getDflt() == null) {
            throw new IllegalArgumentException("Invalid DFME-RTNE entity data");
        }

        Long flightId = entity.getDflt().getFlightId();
        if (flightId == null) {
            throw new IllegalArgumentException("Flight ID is missing in DFME-RTNE data");
        }

        try {
            // 1. 插入消息元数据
            dfmeRtneMapper.insertMeta(entity);

            // 2. 检查航班是否存在
            if (dfmeRtneMapper.checkFlightExists(flightId) == 0) {
                logger.warn("Flight with ID {} not found, inserting new record", flightId);
                dfmeRtneMapper.insertFlightBase(entity);
            } else {
                // 航班存在则更新
                dfmeRtneMapper.updateFlightBase(entity);
            }

            // 3. 插入异常信息（使用自增列）
            dfmeRtneMapper.insertFlightIrregularity(entity);

            logger.info("Successfully processed DFME-RTNE for flight ID: {}", flightId);
        } catch (DataIntegrityViolationException e) {
            logger.error("Data integrity violation while processing flight ID: {}", flightId, e);
            throw new RuntimeException("Data integrity error: " + e.getCause().getMessage());
        } catch (Exception e) {
            logger.error("Unexpected error while processing flight ID: {}", flightId, e);
            throw new RuntimeException("Database operation failed: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeRtneEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeRtneEntity.class);
            parseAndSave(entity);

            return "DFME-RTNE data processed successfully. Flight ID: " +
                    entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-RTNE XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-RTNE XML: " + e.getMessage());
        }
    }
}